package com.atguigu.java2;

/**
 * 经典的生产者/消费者问题
 * <p>
 * 1.是否有多线程问题？是，生产者线程、消费者线程
 * 2.是否有共享数据？是，店员（或者产品）
 * 3.如何解决线程的安全问题？同步机制，有三种方法：
 * 4.是否涉及到线程的通信？是
 *
 * @Description
 * @Author codingBee
 * @Date 2020/9/2/22:02
 */
public class ProductTest {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Producer producer = new Producer(clerk);
        producer.setName("生产者");
        Consumer consumer = new Consumer(clerk);
        consumer.setName("消费者");
        producer.start();
        consumer.start();
    }
}

//店员
class Clerk {
    //生产的产品数
    private int productNum = 0;

    //生产产品
    public synchronized void produceProduct() {
        if (productNum < 20) {
            productNum++;
            System.out.println(Thread.currentThread().getName() + "开始生产第" + productNum + "个产品");
            notify();
        } else {
            //等待
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //消费产品
    public synchronized void consumeProduct() {
        if (productNum > 0) {
            System.out.println(Thread.currentThread().getName() + "开始消费第" + productNum + "个产品");
            productNum--;
            notify();
        }else{
            //等待
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

//生产者
class Producer extends Thread {
    private Clerk clerk;

    public Producer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        System.out.println(getName() + "开始生产产品");
        while (true) {
            try {
                sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.produceProduct();
        }
    }
}

//消费者
class Consumer extends Thread {
    private Clerk clerk;

    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        System.out.println(getName() + "开始消费产品");
        while (true) {
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.consumeProduct();
        }
    }
}
